<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8">
 <title>添加用户</title>
 <link rel="stylesheet" href="/public/layui/css/layui.css">
 <style>
  .layui-form-item {
   margin-bottom: 10px;
   width: 80%;
  }

  .footer_btn {
   display: flex;
   justify-content: flex-end;
   position: fixed;
   right: 20px;
   bottom: 20px;
  }

  .imgs {
   margin-top: 10px;
  }

  .imgs>div {
   position: relative;
   width: 120px;
   height: 120px;
  }

  .imgs>div:hover .del {
   display: block;
  }

  .del {
   position: absolute;
   top: 5px;
   right: 5px;
   cursor: pointer;
   display: none;
  }

  .layui-form-item .imgs img {
   width: 120px;
   height: 120px;
  }
 </style>
</head>

<body>
 <form class="layui-form" action="">

  <div id="head" style="padding-bottom:80px ;overflow: hidden;">
   <blockquote style="padding-top: 20px;height: 100%;" class="layui-fluid layui-form news_search margin-bottom-0"
    lay-filter="detailForm">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 5px;margin-bottom: 5px;">
     <legend>用户信息</legend>
    </fieldset>
    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
     <p class="layui-bg-gray" style="padding: 5px 10px">温馨提示：带<span style="color: red;"> *
      </span>为必填项，请填写真实信息</p>
    </div>
    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
     <br />
    </div>

    <div class="layui-form-item layui-col-md8">
     <label class="layui-form-label" style="padding: 5px 15px;"><span style="color: red;">*
      </span>用户名:</label>
     <div class="layui-input-block">
      <input type="text" id="username" name="username" required lay-verify="required" class="layui-input"
       style="z-index: 9;" />
     </div>
    </div>

    <div class="layui-form-item layui-col-md8">
     <label class="layui-form-label" style="padding: 5px 15px;">
      <span style="color: red;">*
      </span>密码:</label>
     <div class="layui-input-block">
      <input type="text" id="password" name="password" required lay-verify="required" class="layui-input"
       style="z-index: 9;" />
     </div>
    </div>

    <div class="layui-form-item layui-col-md8">
     <label class="layui-form-label" style="padding: 5px 15px;"><span style="color: red;">*
      </span>头像:</label>
     <div class="layui-input-block">
      <button type="button" class="layui-btn" id="upload" name="img">
       <i class="layui-icon">&#xe67c;</i>上传头像
      </button> (<a href="javascript:;">仅可上传一张图片</a>)
      <div class="imgs"></div>
     </div>
    </div>
  </div>
  </blockquote>
  <div class="footer_btn">
   <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="btnSave" id="btnSaves" type="submit">保存</button>
  </div>
 </form>

 <script src="/public/layui/layui.js"></script>
 <script>
  layui.config({
   base: '/public/js/'
  }).use(['layer', 'form', 'jquery', 'table', 'upload', 'commonLayer'], function () {
   var layer = layui.layer, form = layui.form, $ = layui.jquery;
   var table = layui.table;
   var upload = layui.upload;
   var commonLayer = layui.commonLayer();
   var urlSearch = commonLayer.urlSearch()
   let imgList = [];
   const user = JSON.parse(sessionStorage.getItem('user') || '{}')

   if (urlSearch && urlSearch.id) {
    $.ajax({
     method: 'get',
     url: `/api/auth/user/${urlSearch.id}`,
     headers: {
      Authorization: 'Bearer ' + sessionStorage.getItem('token')
     },
     success: (ret) => {
      if (ret.success) {
       const data = ret.data
       $('#username').val(data.username)
       // $('#password').val(data.password) //修改不显示密码
       if (data.img) {
        imgList = data.img.split(',')
        imgView()
       }
      } else {
       commonLayer.errorMsg(ret.message || '网络开了会差,请稍后再试')
      }
     }
    })
   }
   const imgView = () => {
    let str = ''
    $('#upload').attr('disabled', imgList.length > 0)

    imgList.forEach((c, i) => {
     str += `<div><img src="${c}" alt=""><i class="layui-icon del" inx="${i}" style="font-size: 24px; color: #1E9FFF;">&#x1006;</i>  </div>`
    })
    $('.imgs').html(str)
    $('.del').click(function () {
     console.log('del');
     const inx = parseInt($(this).attr('inx'))
     console.log(inx);
     imgList = imgList.filter((c, j) => j != inx)
     imgView()
    })
   }
   var uploadInst = upload.render({
    elem: '#upload',
    url: '/api/upload',
    accept: 'images',
    number: 1,
    multiple: false,
    done: function (ret) {
     console.log(ret);
     if (ret.success) {
      imgList.push(ret.data.url)
      imgView()
     }
     //上传完毕回调
    }, error: function () {
     //请求异常回调
    }
   });

   form.on('submit', function (data) {
    if (!imgList.length) {
     commonLayer.errorMsg('图片不能为空')
     return false;
    }
    data.field.img = imgList.join(',')
    console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
    var load = layer.load(1);
    delete data.field.file;
    $.ajax({
     method: urlSearch.id ? 'put' : 'post',
     url: urlSearch.id ? `/api/auth/user/${urlSearch.id}` : `/api/auth/user`,
     data: data.field,
     dataType: 'json',
     headers: {
      Authorization: 'Bearer ' + sessionStorage.getItem('token')
     },
     success: (ret) => {
      layer.close(load)
      if (ret.success) {
       if (urlSearch.id && data.field.username == user.username) {
        $.ajax({
         method: 'post',
         url: `/api/login`,
         data: data.field,
         dataType: 'json',
         success: (ret) => {
          layer.close(load)
          if (ret.success) {
           sessionStorage.setItem('token', ret.data.token)
           sessionStorage.setItem('user', JSON.stringify(ret.data.user))
           // commonLayer.successMsg('登录成功')
           // window.location.href = "/";
          } else {
           commonLayer.errorMsg(ret.message || '网络开了会差,请稍后再试')
          }
         }
        })
       }
       commonLayer.successMsg('操作成功')
       var index = parent.layer.getFrameIndex(window.name);
       parent.layer.close(index);
       parent.reloadTable();
      } else {
       commonLayer.errorMsg(ret.message || '网络开了会差,请稍后再试')
      }
     }
    })
    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
   });

  });
 </script>
</body>

</html>